package com.conference.service.impl;

import com.conference.dto.LoginResponse;
import com.conference.dto.RegisterRequest;
import com.conference.entity.ConferenceUser;
import com.conference.repository.UserRepository;
import com.conference.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.Optional;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    private static final String JWT_SECRET = "your-secret-key";
    private static final long JWT_EXPIRATION = 86400000L; // 24 hours

    @Override
    public LoginResponse login(String username, String password, Byte permissionId) {
        // 查找用户
        Optional<ConferenceUser> userOpt = userRepository.findByUsername(username);
        
        if (userOpt.isEmpty()) {
            return LoginResponse.error("用户不存在");
        }

        ConferenceUser user = userOpt.get();

        // 直接比较明文密码
        if (!password.equals(user.getPassword())) {
            return LoginResponse.error("密码错误");
        }

        // 验证角色权限
        if (permissionId == null) {
            return LoginResponse.error("请选择登录角色");
        }
        
        if (!permissionId.equals(user.getPermissionId())) {
            String roleText = permissionId == 1 ? "会议组织者" : "参会人员";
            return LoginResponse.error("您没有" + roleText + "的权限，请选择正确的角色");
        }

        // 生成 JWT token
        String token = generateToken(user);

        // 清除密码字段再返回用户信息
        user.setPassword(null);
        return LoginResponse.success(token, user);
    }

    @Override
    public LoginResponse register(RegisterRequest request) {
        // 检查用户名是否已存在
        if (userRepository.findByUsername(request.getUsername()).isPresent()) {
            return LoginResponse.error("用户名已存在");
        }

        // 创建新用户
        ConferenceUser newUser = new ConferenceUser();
        newUser.setUsername(request.getUsername());
        newUser.setPassword(request.getPassword());  // 直接存储明文密码
        newUser.setEmail(request.getEmail());
        newUser.setPermissionId(request.getPermissionId());
        newUser.setPhone(request.getPhone()); // 设置手机号
        
        // 设置默认值
        newUser.setFullName(request.getUsername()); // 默认使用用户名作为全名
        
        // 保存用户
        try {
            newUser = userRepository.save(newUser);
        } catch (Exception e) {
            return LoginResponse.error("注册失败：" + e.getMessage());
        }

        // 生成 JWT token
        String token = generateToken(newUser);

        // 清除密码字段再返回用户信息
        newUser.setPassword(null);
        return LoginResponse.success(token, newUser);
    }

    private String generateToken(ConferenceUser user) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + JWT_EXPIRATION);

        return Jwts.builder()
                .setSubject(Long.toString(user.getUserId()))
                .claim("username", user.getUsername())
                .claim("permissionId", user.getPermissionId())
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, JWT_SECRET)
                .compact();
    }
} 